package com.example.choupaiapp.main.util;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.choupaiapp.R;
import com.example.choupaiapp.main.activity.publish.UserListActivity;
import com.example.choupaiapp.main.bean.UserModelListBean;
import com.orhanobut.logger.Logger;
import com.shuyu.textutillib.RichEditBuilder;
import com.shuyu.textutillib.RichEditText;
import com.shuyu.textutillib.listener.OnEditTextUtilJumpListener;
import com.shuyu.textutillib.model.UserModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


public class PublishDialog extends DialogFragment implements View.OnClickListener {

    private RichEditText commentEditText;
    private ImageView anonymous_iv;
    private InputMethodManager inputMethodManager;
    private DialogPublishDataCallback dataCallback;
    private LinearLayout anonymous_ll;
    private LinearLayout remind_ll;
    private LinearLayout vote_ll;
    private List<UserModel> nameListEd;
    private int atFlag = 2222;//1111 输入跳转  2222 点击跳转
    private UserModelListBean userModelListBean;

    @Override
    public void onAttach(Context context) {
        if (!(getActivity() instanceof DialogPublishDataCallback)) {
            throw new IllegalStateException("DialogFragment 所在的 activity 必须实现 DialogPublishDataCallback 接口");
        }
        super.onAttach(context);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog mDialog = new Dialog(getActivity(), R.style.BottomDialog);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setContentView(R.layout.dialog_publish_send);
        mDialog.setCanceledOnTouchOutside(true);

        Window window = mDialog.getWindow();
        WindowManager.LayoutParams layoutParams;
        if (window != null) {
            layoutParams = window.getAttributes();
            layoutParams.gravity = Gravity.BOTTOM;
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(layoutParams);
        }

        EventBus.getDefault().register(this);

        commentEditText = (RichEditText) mDialog.findViewById(R.id.edit);
        anonymous_iv = (ImageView) mDialog.findViewById(R.id.anonymous_iv);
        anonymous_ll = (LinearLayout) mDialog.findViewById(R.id.anonymous_ll);
        vote_ll = (LinearLayout) mDialog.findViewById(R.id.vote_ll);
        remind_ll = (LinearLayout) mDialog.findViewById(R.id.remind_ll);

        nameListEd = new ArrayList<>();

        userModelListBean = new UserModelListBean();

        RichEditBuilder richEditBuilder = new RichEditBuilder();
        richEditBuilder.setEditText(commentEditText)
                .setUserModels(nameListEd)
                .setColorAtUser(getString(R.string.remind_color))
                .setEditTextAtUtilJumpListener(new OnEditTextUtilJumpListener() {
                    @Override
                    public void notifyAt() {
                        atFlag = 1111;
                        userModelListBean.setUserModels(commentEditText.getRealUserList());
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("userModels", userModelListBean);
                        startActivity(UserListActivity.class, bundle);
                    }

                    @Override
                    public void notifyTopic() {
                    }
                })
                .builder();

        fillEditText();
        setSoftKeyboard();

        anonymous_ll.setOnClickListener(this);
        vote_ll.setOnClickListener(this);
        remind_ll.setOnClickListener(this);

        return mDialog;
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("pubish_@_user")) {
            UserModel userModel = new UserModel();
            userModel.setUser_id(event.split(":")[2]);
            userModel.setUser_name(event.split(":")[1]);
            if (atFlag == 1111) {
                commentEditText.resolveAtResultByEnterAt(userModel);
            } else {
                commentEditText.resolveAtResult(userModel);
            }
        }
    }

    private void startActivity(Class<?> cls,Bundle bundle) {
        Intent intent = new Intent(getActivity(), cls);
        intent.putExtras(bundle);
        getActivity().startActivity(intent);
    }

    private void fillEditText() {
        dataCallback = (DialogPublishDataCallback) getActivity();
        if (!TextUtils.isEmpty(dataCallback.getCommentText())) {
            nameListEd.clear();
            nameListEd.addAll(dataCallback.getNameList());
            commentEditText.resolveInsertText(getActivity(), dataCallback.getCommentText(), nameListEd, null);
        } else {
            commentEditText.setText("");
        }
        commentEditText.setSelection(dataCallback.getCommentText().length());

        if (dataCallback.isAnonymous() == 0) {
            dataCallback.setAnonymous(dataCallback.isAnonymous());
            anonymous_iv.setImageResource(R.mipmap.icon_anonymous_unselect);
        } else {
            dataCallback.setAnonymous(dataCallback.isAnonymous());
            anonymous_iv.setImageResource(R.mipmap.icon_anonymous_select);
        }


    }

    private void setSoftKeyboard() {
        commentEditText.setFocusable(true);
        commentEditText.setFocusableInTouchMode(true);
        commentEditText.requestFocus();

        //为 commentEditText 设置监听器，在 DialogFragment 绘制完后立即呼出软键盘，呼出成功后即注销
        commentEditText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    if (inputMethodManager.showSoftInput(commentEditText, 0)) {
                        commentEditText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.anonymous_ll:
                if (dataCallback.isAnonymous() == 0) {
                    dataCallback.setAnonymous(1);
                    anonymous_iv.setImageResource(R.mipmap.icon_anonymous_select);
                } else {
                    dataCallback.setAnonymous(0);
                    anonymous_iv.setImageResource(R.mipmap.icon_anonymous_unselect);
                }
                break;
            case R.id.vote_ll:
                if (dataCallback.isVote() == 0) {
                    dataCallback.setVote(1);
                } else {
                    dataCallback.setVote(1);
                }
                dismiss();
                break;
            case R.id.remind_ll:
                atFlag = 2222;
                userModelListBean.setUserModels(commentEditText.getRealUserList());
                Bundle bundle = new Bundle();
                bundle.putSerializable("userModels", userModelListBean);
                startActivity(UserListActivity.class, bundle);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        dataCallback.setNameList(commentEditText.getRealUserList());
        dataCallback.setCommentText(commentEditText.getRealText());
        dataCallback.setAnonymous(dataCallback.isAnonymous());
        super.onDismiss(dialog);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        dataCallback.setNameList(commentEditText.getRealUserList());
        dataCallback.setCommentText(commentEditText.getRealText());
        dataCallback.setAnonymous(dataCallback.isAnonymous());
        super.onCancel(dialog);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}